<?php
class UserManager {
	public static function reg($user) {
		LogManager::setLogs(__CLASS__.".".__METHOD__);
		if(UserManager::IsValidate($user)){
			
			if(UserManager::IsExistUserName($user->username)){
				LogManager::setErrLogs(__CLASS__.".".__METHOD__.": Username is already in used");
				return -2;
			}
			
			if(UserManager::IsExistEmail($user->email)){
				LogManager::setErrLogs(__CLASS__.".".__METHOD__.": Email is already in used");
				return -3;
			}
				
			$sql = "INSERT INTO `user`(`username`,`password`,`fname`,`lname`,`email`,`mobile`,`createdatetime`,`updatedatetime`,`status`)";
			$sql = $sql." VALUES(?, ?, ?, ?, ?, ?, now(), NULL, 1)";
			$sqlQuery = new SqlQuery($sql);
			$sqlQuery->set($user->username);
			$sqlQuery->set(Secure::ToEncodePassword($user->password));
			$sqlQuery->set($user->fname);
			$sqlQuery->set($user->lname);
			$sqlQuery->set($user->email);
			$sqlQuery->set($user->mobile);
			
			return QueryExecutor::executeInsert($sqlQuery);
		}else{
			LogManager::setErrLogs(__CLASS__.".".__METHOD__.": Validate Fail");
			return -1;
		}
	}
	
	public static function IsExistUserName($username){
		$sqlQuery = new SqlQuery("SELECT COUNT(*) as CNT FROM `user` WHERE LOWER(username) = ?");
		$sqlQuery->set(strtolower($username));
		return QueryExecutor::queryForString($sqlQuery);
	}
	
	public static function IsExistEmail($email){
		$sqlQuery = new SqlQuery("SELECT COUNT(*) as CNT FROM `user` WHERE LOWER(email) = ?");
		$sqlQuery->set(strtolower($username));
		return QueryExecutor::queryForString($sqlQuery);
	}
	
	public static function search($user){
		$sql = "SELECT * FROM `user` WHERE 1=1";
		if(strlen($user->username) > 0)
			$sql .= " AND username like '%".$user->username."%'";
		if(strlen($user->fname) > 0)
			$sql .= " AND fname like '%".$user->fname."%'";
		if(strlen($user->lname) > 0)
			$sql .= " AND lname like '%".$user->lname."%'";
		if(strlen($user->email) > 0)
			$sql .= " AND email like '%".$user->email."%'";
		if(strlen($user->mobile) > 0)
			$sql .= " AND mobile like '%".$user->mobile."%'";
		return QueryExecutor::execute(new SqlQuery($sql));
	}
	
	private static function IsValidate($user){
		return ((isset($user->username) && strlen($user->username) > 0)
		&& (isset($user->password) && strlen($user->password) > 0)
		&& (isset($user->email) && strlen($user->email) > 0) && Validater::isValidEmail($user->email));
	}
}